import { Service } from 'egg';
import { Admin } from '../model/Admin';
import { Setting } from '../model/Setting';
import * as md5 from 'blueimp-md5';

/**
 * Test Service
 */
export default class System extends Service {

    /**
     * 初始化系统
     */
    public async initSystem() {
        const settingConfig = this.config.systemDefaultConfig.setting;
        const userConfig = this.config.systemDefaultConfig.user;
        // TODO 检查是否载入了默认配置，如果没有，则插入
        const settingList = await this.ctx.model.Setting.findAll<Setting>();
        const defaultSettingKeys = Object.keys(settingConfig);
        const insertSettingList: Setting[] = [];
        defaultSettingKeys.forEach((key) => {
            let findIndex: number = -1;
            for (let i = 0; i < settingList.length; i++) {
                const item = settingList[i];
                // tslint:disable-next-line:no-string-literal
                if (item['setting_key'] === key) {
                    findIndex = i;
                }
            }
            if (findIndex === -1) {
                const tempSetting = new Setting();
                tempSetting.setting_id = this.ctx.helper.genUUID();
                tempSetting.setting_key = key;
                tempSetting.setting_value = settingConfig[key];
                insertSettingList.push(tempSetting);
            }
        });
        // TODO 检查是否存在默认管理员用户，如果没有则插入
        const tran = await this.ctx.model.transaction();
        try {
            const admin = new Admin();
            const resultAdmin = await this.service.adminService.searchAdmin(userConfig.defaultUsername);
            if (!resultAdmin) {
                admin.admin_token = this.ctx.helper.genUUID();
                admin.admin_username = userConfig.defaultUsername;

                admin.admin_password = md5(userConfig.defaultPassword + 'linglan');
                admin.created_by = 'system';
                admin.admin_id = this.ctx.helper.genUUID();
                admin.is_delete = '1';
                await this.ctx.model.Admin.create(admin, { transaction: tran });
            }
            if (insertSettingList.length > 0) {
                await this.ctx.model.Setting.bulkCreate(insertSettingList, { transaction: tran });
            }
            await tran.commit();
        } catch (e) {
            await tran.rollback();
            this.ctx.logger.error(e);
        }
    }

}
